<!-- eslint-disable vue/no-useless-template-attributes -->
<template>
	<div class="app-container">
		<el-col :span="8">
			<div class="send-head">
				<p>系统默认发件人</p>
				<el-select v-model="defaultSender" placeholder="请选择系统默认发件人" style="width: 60%" filterable>
					<el-option v-for="item in tableData" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
				</el-select>
				<el-button plain @click="saveSetting">保存</el-button>
			</div>
		</el-col>
		<el-button plain @click="addSetting">添加发件人</el-button>

		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="getList"
			@sortChangeHandler="getList"
		>
		</YdTable>
		<!-- 添加/修改发件人对话框 -->
		<el-dialog v-model="open" title="发件人账户设置" width="500px" append-to-body center :close-on-click-modal="false" @close="open = false">
			<yd-form ref="dialogForm" class="yd-form-wraper" :model="dialogFormData" :options="dialogFormOptions">
				<template #form-footer>
					<div>
						<span style="font-size: 12px; margin-left: 130px">*QQ邮箱请输入授权码</span>
					</div>
					<div class="dialog-footer">
						<el-button type="success" @click="sendDialog">发送测试邮件</el-button>

						<el-button type="primary" :disabled="disabledSubmit" @click="submitDialogForm">确 定</el-button>
						<el-button @click="handleCancel">取 消</el-button>
					</div>
				</template>
			</yd-form>
		</el-dialog>
		<!-- 发送测试邮件对话框 -->
		<el-dialog v-model="sendOpen" title="发送测试邮件" width="500px" append-to-body center :close-on-click-modal="false" @close="sendOpen = false">
			<el-form ref="emaildialogForm" :model="emailForm" label-width="150px">
				<el-form-item
					prop="email"
					style="margin-right: 20px"
					label="邮件接收人地址"
					:rules="[
						{
							required: true,
							message: '请输入邮件接收人地址',
							trigger: 'blur',
						},
						{
							type: 'email',
							message: '请输入正确的邮箱地址',
							trigger: 'blur',
						},
					]"
				>
					<el-input v-model="emailForm.email" placeholder="请输入邮件接收人地址" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="sendEmail">确 定</el-button>
				<el-button @click="sendOpen = false">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="tsx" name="SendEmail" setup>
import { ref, reactive, toRefs, onMounted, onActivated, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useCurrentInstance from '@/utils/useCurrentInstance';
import {
	addPushObjectEmailAdress,
	getPushObjectEmailAdressList,
	updatePushObjectEmailAdress,
	deletePushObjectEmailAdress,
	savePushObjectDefaultEmailAdress,
	pushObjectSendTestEmail,
} from '@/api/ops-workbench/timeSchedule/globalSetting';
const { proxy } = useCurrentInstance();
const router = useRouter();
const route = useRoute();
let searchFormData = reactive<anyObj>({
	// taskName: taskName.value,
});
const options = ref([]);
let defaultSender = ref();
const dialogForm = ref();
const emaildialogForm = ref();

// 禁止保存
const disabledSubmit = ref(true);

// 添加发件人弹窗配置
let open = ref(false);
// 发送测试邮件弹窗配置
let sendOpen = ref(false);
let emailForm = reactive<anyObj>({
	email: '',
});
// 新增表单
const dialogFormData = ref<FormModelType>({});

const dialogFormOptions = ref<any[]>([
	{
		type: 'select',
		label: '邮件服务器',
		prop: 'emailHost',
		span: 24,
		isInitValue: false,
		api: {
			name: 'queryDictByType',
			params: 'reportform_email_domain',
		},
		// children: [
		// 	{ value: 'smtp.yuandian.com', label: 'foxmail' },
		// 	{ value: 'smtp.163.com', label: '163邮箱' },
		// ],
		rules: [
			{
				required: true,
				message: '请选择邮件服务器',
				trigger: 'blur',
			},
		],
		attrs: {
			disabled: false,
		},
	},
	{
		type: 'input',
		label: '端口',
		prop: 'emailPort',
		span: 24,
		rules: [
			{
				required: true,
				message: '请输入端口',
				trigger: 'blur',
			},
		],
	},
	{
		type: 'select',
		label: '加密方式',
		prop: 'encryptType',
		span: 24,
		isInitValue: false,
		selectKey: 'value',
		selectLabel: 'label',
		children: [
			{ value: 1, label: 'SSL加密' },
			{ value: 2, label: 'TSL加密' },
			{ value: 3, label: '不加密' },
		],
	},

	{
		type: 'input',
		label: '发件人地址',
		prop: 'email',
		span: 24,
		rules: [
			{
				required: true,
				message: '请输入发件人地址',
				trigger: 'blur',
			},
			{
				type: 'email',
				message: '请输入正确的邮箱地址',
				trigger: 'blur',
			},
		],
	},
	{
		type: 'input',
		label: '密码/授权码',
		prop: 'password',
		span: 24,
		show: true,
		attrs: {
			type: 'password',
			showPassword: true,
		},
		rules: [
			{
				min: 6,
				max: 20,
				message: '长度在 6 到 20 个字符',
				trigger: 'blur',
			},
			{
				required: true,
				message: '请输入密码',
				trigger: 'blur',
			},
		],
	},

	{
		type: 'input',
		label: '显示姓名',
		prop: 'nickName',
		span: 24,
	},
]);
const tableData = ref<any[]>([]);
const tableConfig = reactive({
	columns: [
		{
			label: '发件地址',
			prop: 'email',
		},
		{
			label: '显示姓名',
			prop: 'nickName',
			sortable: true,
		},
		{
			label: '操作',
			prop: '',
			width: 300,
			operation: [
				{
					text: '修改',
					handler: (scope: anyObj) => handleEdit(scope.row),
					// permi: ['metadata:dataShow:download'],
				},
				{
					text: '删除',
					handler: (scope: anyObj) => handleDelete(scope.row),
					// permi: ['metadata:dataShow:delete'],
				},
			],
		},
	],
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	loading: false,
});

onMounted(() => {
	searchHandler();
});

function searchHandler() {
	console.log(searchFormData);
	tableConfig.pagination!.pageNum = 1;
	getList();
}

function getList() {
	tableConfig.loading = true;
	getPushObjectEmailAdressList(searchFormData)
		.then((res: ApiResponse) => {
			if (res.code !== 0) {
				proxy?.$message.error(res.msg);
				return;
			}
			tableConfig.pagination!.total = res.data.total;
			tableData.value = res.data.records;
			tableData.value.forEach((item: any) => {
				if (item.isDefault === 1) {
					defaultSender.value = item.id;
				}
			});
		})
		.finally(() => {
			tableConfig.loading = false;
		});
}

// 保存
function saveSetting() {
	if (defaultSender.value === null) return;
	savePushObjectDefaultEmailAdress(defaultSender.value).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy?.$message.error(res.msg);
			return;
		}
		proxy?.$message.success('保存成功');
	});
}

// 添加发件人弹窗
function addSetting() {
	dialogFormOptions.value[0].attrs.disabled = false;
	disabledSubmit.value = true;
	open.value = true;
	nextTick(() => {
		resetForm();
	});
}
// 删除
function handleDelete(row: anyObj) {
	proxy.$modal
		.confirm('确定删除发件人' + row.nickName + '吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deletePushObjectEmailAdress(row.id).then((res: ApiResponse) => {
				if (res.code !== 0) {
					proxy.$message.error(res.msg);
					return;
				}
				proxy?.$message.success('删除成功');
				getList();
			});
		});
}

function handleCancel() {
	open.value = false;
}

// 修改
function handleEdit(row: anyObj) {
	dialogFormOptions.value[0].attrs.disabled = true;
	disabledSubmit.value = false;
	open.value = true;
	nextTick(() => {
		resetForm();
		dialogFormData.value = JSON.parse(JSON.stringify(row));
	});
}

function submitDialogForm() {
	dialogForm.value?.validate((valid: boolean, _msg: any) => {
		if (valid) {
			open.value = false;
			if (dialogFormData.value.id) {
				// 修改
				updatePushObjectEmailAdress(dialogFormData.value).then((res: ApiResponse) => {
					if (res.code !== 0) {
						proxy?.$message.error(res.msg);
						return;
					}
					proxy?.$message.success('修改成功');
					getList();
				});
			} else {
				// 新增
				addPushObjectEmailAdress(dialogFormData.value).then((res: ApiResponse) => {
					if (res.code !== 0) {
						proxy?.$message.error(res.msg);
						return;
					}
					proxy?.$message.success('保存成功');
					getList();
				});
			}
		}
	});
}
function sendDialog() {
	dialogForm.value?.validate((valid: boolean, _msg: any) => {
		if (valid) {
			sendOpen.value = true;
			nextTick(() => {
				emaildialogForm.value?.resetFields();
				emailForm.email = '';
			});
		}
	});
}
// 发送测试邮件
function sendEmail() {
	emaildialogForm.value?.validate((valid: boolean, _msg: any) => {
		if (valid) {
			sendOpen.value = false;
			const params = {
				host: dialogFormData.value.emailHost,
				port: dialogFormData.value.emailPort,
				from: dialogFormData.value.email,
				password: dialogFormData.value.password,
				nickname: dialogFormData.value.nickName,
				subject: '测试邮件',
				content: '恭喜您！您的邮件服务器已经配置成功',
				address: [emailForm.email],
			};
			pushObjectSendTestEmail(params).then((res: ApiResponse) => {
				if (res.code !== 0) {
					proxy?.$message.error(res.msg);
					return;
				}
				proxy?.$message.success('发送成功');
				disabledSubmit.value = false;
			});
		}
	});
}
function resetForm() {
	dialogForm.value?.resetFields();

	for (let key in dialogFormData) {
		dialogFormData.value[key] = '';
	}
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
	.send-head {
		display: flex;
		padding: 10px 0 20px;
		font-size: 14px;
		justify-content: space-between;
		align-items: center;
		:deep(.el-input) {
			width: 100%;
		}
	}
}
.dialog-footer {
	display: flex;
	justify-content: center;
	margin-top: 20px;
	// padding: 0 30px;
}
</style>
